﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using Cloud.Core.Model;
using Cloud.Core.Response;
using Cloud.Core.AuthUser;
using Microsoft.EntityFrameworkCore.Internal;
using Cloud.Core.Bizlogic;
using Cloud.Core.ModelSearch;
using System.Threading;

namespace Cloud.Core.Controllers
{
    /// <summary>
    /// 代码项管理
    /// </summary> 
    [Route("api/v1/[controller]")]
    [ApiController]
    public class DataCodeController : ControllerBase
    {
        private readonly CloudDataBase _context;
        private readonly ModOperate.Mod _thisModel = ModOperate.Mod.MBasicInfo;
        public DataCodeController(CloudDataBase context)
        {
            _context = context;
        }

        #region base     

        #region 获取分页信息
        /// <summary>
        /// 获取分页信息
        /// </summary>
        /// <returns></returns>
        [Route("GetStructList")]
        [HttpPost]
        public async Task<JsonResponse<DataList<CodeMain>>> GetStructList([FromHeader] string Authorization, sField sPage)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<DataList<CodeMain>>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            response.Data = new DataList<CodeMain>();
            var listQuery = _context.Codemain.Where(t => 1==1);
            if (!string.IsNullOrEmpty(sPage.Field2))
            {
                listQuery = listQuery.Where(t => t.Code == sPage.Field2);
            }
            if (!string.IsNullOrEmpty(sPage.Field1))
            {
                listQuery = listQuery.Where(t => t.Name.Contains(sPage.Field1)|| t.Value.Contains(sPage.Field1));
            }
            response.Data.Total = await listQuery.CountAsync().ConfigureAwait(false);
            var list = await listQuery
                   .OrderBy(t => t.Iorder)
                   .ToArrayAsync()
                   .ConfigureAwait(false);
            response.Data.Count = list.Length;
            response.Data.List = list;
            response.Status = ResponseStatus.Success;
            response.Msg = "查询成功";

            return response;
        }
        #endregion

        #region 代码项添加
        /// <summary>
        /// 代码项添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Route("CodeMainAdd")]
        [HttpPost]
        public async Task<JsonResponse> CodeMainAdd([FromHeader] string Authorization, CodeMain entity = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }

            var data = await _context.Codemain.FirstOrDefaultAsync(t => t.Id == entity.Id).ConfigureAwait(false);
            if (data != null)
            {
                response.Msg = "添加失败,该代码项已存在";
                response.Status = ResponseStatus.MultipleData;
                return response;
            }
            var arr = _context.Codemain.Select(t => t.Id).ToArray();


            _context.Set<CodeMain>().Add(entity);
            //int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "代码项添加成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "添加失败";
                response.Status = ResponseStatus.ParameterError;
            }
            string et = response.Msg + "-实体内容:" + new Helper().ObjectToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));


            return response;
        }
        #endregion

        #region 代码项编辑
        /// <summary>
        /// 代码项编辑 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("CodeMainUpdate")]
        public async Task<JsonResponse> CodeMainUpdate([FromHeader] string Authorization, CodeMain entity = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            var dataCount = _context.Set<CodeMain>().Where(c => c.Id == entity.Id).Count();

            //var data = await _context.CodeMain.FirstOrDefaultAsync(t => t.Id == entity.Id).ConfigureAwait(false);
            if (dataCount == 0)
            {
                response.Msg = "修改失败,数据不存在";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            _context.Set<CodeMain>().Update(entity);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "代码项修改成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "修改失败";
                response.Status = ResponseStatus.ProcessFail;
            }
            string et = response.Msg + "-修改数据:" + new Helper().objToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));

            return response;
        }

        #endregion

        #region 代码项删除
        /// <summary>
        /// 代码项删除 
        /// </summary>
        /// <param name="aaa"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("CodeMainDel")]
        public async Task<JsonResponse> CodeMainDel([FromHeader] string Authorization, string ids = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (ids.Length == 0)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
            }

            string[] arr = ids.TrimEnd(',').Split(',');
            Guid[] barr = new Guid[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                barr[i] = new Guid(arr[i]);
            }
            var CodeMains = _context.Codemain.Where(c => barr.Contains(c.Id));

            var dataCount = CodeMains.Count();
            if (dataCount == 0)
            {
                response.Msg = "数据不存在,不允许删除";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            string delArr = new Helper().objToJson(CodeMains);

            _context.Codemain.RemoveRange(CodeMains);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "代码项删除成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "代码项删除失败";
                response.Status = ResponseStatus.ParameterError;
            }
            delArr = response.Msg + "-删除集合:" + delArr;
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, delArr), RouteData.Values.Values.Join(","));

            return response;
        }
        #endregion        
        #endregion
    }
}
